/*
 * 任意面标绘功能
 * @Author: Wang jianLei
 * @Date: 2023-01-17 15:04:31
 * @Last Modified by: Wang JianLei
 * @Last Modified time: 2023-01-17 22:51:49
 */
const Cesium = window.Cesium;

import { newSessionid, getCatesian3FromPX,hexToCesiumColor,createRemindertip } from '../../plotCommon';
const CreateRandom = (
  viewer: any,
  handler: any,
  resultList: any[],
  options: any,
  callback?: Function
) => {
    const id = newSessionid();
    const onground = options.onground || true;
    var viewer = viewer;
    var code=options.code||newSessionid()
    var style=options.style||Cesium.Color.White
    var instyle=options.instyle||Cesium.Color.White
    var alfa=options.alfa||1
  let toolTip:any
  if (viewer.entities.getById(id))
    throw new Error('the id parameter is an unique value');
  toolTip = '左键点击开始绘制';
  let anchorpoints: any[] = [];
  let polygon: any = undefined;
  // 左键点击事件
  handler.setInputAction((event: any) => {
    let pixPos = event.position;
    let cartesian = getCatesian3FromPX(viewer, pixPos);
    if (anchorpoints.length == 0) {
      toolTip = '左键双击结束绘制';
      anchorpoints.push(cartesian);
      let dynamicPositions = new Cesium.CallbackProperty(function () {
        return new Cesium.PolygonHierarchy(anchorpoints);
      }, false);
      polygon = viewer.entities.add({
        name: 'FreePolygon',
        code:code,
        id: newSessionid(),
        polygon: {
          hierarchy: dynamicPositions,
          material:hexToCesiumColor(instyle,alfa),
          outline: true,
          outlineColor: hexToCesiumColor(style,1),
          heightReference: onground
            ? Cesium.HeightReference.CLAMP_TO_GROUND
            : Cesium.HeightReference.NONE,
        },
      });
      polygon.GeoType = 'FreePolygon'; //记录对象的类型，用户后续编辑等操作
      polygon.Editable = false; //代表当前对象可编辑,false状态下不可编辑
    }
    anchorpoints.push(cartesian);
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  // 鼠标移动事件
  handler.setInputAction((movement: any) => {
    console.log('鼠标移动事件监测：------创建任意多边形------');
    let endPos = movement.endPosition;
    createRemindertip(toolTip, endPos, true);
    if (Cesium.defined(polygon)) {
      // anchorpoints.pop();
      let cartesian = getCatesian3FromPX(viewer, endPos);
      anchorpoints.push(cartesian);
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  // 左键双击事件
  handler.setInputAction((event: any) => {
    anchorpoints.pop();
    anchorpoints.pop(); //因为是双击结束，所以要pop两次，一次是move的结果，一次是单击结果
    const hierarchyPos = new Cesium.PolygonHierarchy(anchorpoints);
    polygon.PottingPoint = Cesium.clone(hierarchyPos, true); //记录对象的节点数据，用户后续编辑等操作
    resultList.push(polygon);
    handler.destroy();
    createRemindertip(toolTip, event.position, false);
    if (typeof callback == 'function') callback(polygon);
  }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
};
export default CreateRandom;